package cn.leizp.springboot.auth.frontweb.filter;

import cn.leizp.springboot.auth.frontweb.controller.LoginController;
import cn.leizp.springboot.auth.frontweb.entity.Resource;
import cn.leizp.springboot.auth.frontweb.entity.Role;
import cn.leizp.springboot.auth.frontweb.entity.User;
import cn.leizp.springboot.auth.frontweb.service.UserService;
import cn.leizp.springboot.auth.MyToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 登录和注册接口不进行校验
        String requestUri = request.getRequestURI();
        System.out.println(request.getMethod() + ":" + requestUri);

        if (requestUri.endsWith("login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 开始执行权限验证程序
        System.out.println("==开始执行权限验证程序==");

        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            System.out.println("==无token信息，跳转登录页面==");
            response.sendRedirect(LoginController.LoginUrl);
            return;
        }
        System.out.println("==token提取完成==");
        token = token.substring(7);
        String username = MyToken.getUsernameFromToken(token);
        if (username == null) {
            System.out.println("==提取用户名失败，跳转登录页面==");
            response.sendRedirect(LoginController.LoginUrl);
            return;
        }
        User user = userService.getByUsername(username);
        if (user == null) {
            System.out.println("==提取用户信息失败，跳转登录页面==");
            response.sendRedirect(LoginController.LoginUrl);
            return;
        }
        System.out.println("==用户信息获取提取完成==" + user.getUsername());
        String requestUrl = request.getRequestURI();
        boolean hasPermission = false;
        for (Role role : user.getRoles()) {
            for (Resource resource : role.getResources()) {
                if (resource.getUri().equals(requestUrl)) {
                    hasPermission = true;
                    break;
                }
            }
            if (hasPermission) {
                break;
            }
        }
        System.out.println("==权限验证完成==" + hasPermission);
        if (!hasPermission) {
            System.out.println("==用户无权限，跳转登录页面==");
            response.sendRedirect(LoginController.LoginUrl);
            return;
        }
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        System.out.println("==权限验证通过，继续请求处理==");
        filterChain.doFilter(request, response);
    }
}
